package com.andryu.grifika.utils

import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import androidx.activity.ComponentActivity
import androidx.annotation.RequiresApi
import com.andryu.base.LogUtils
import com.andryu.grifika.module.GrifikaDataModule
import java.io.File
import java.nio.file.Files
import java.util.regex.Pattern
import java.util.stream.Collectors

object MiscUtils {

    /**
     * Obtains a list of files that live in the specified directory and match the glob pattern.
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun getFiles(dir: File, glob: String): Array<out String>? {
        val regex = globToRegex(glob)
        val pattern = Pattern.compile(regex)
//        val result: Array<out String>? = dir.list { _, name ->
//            val matcher = pattern.matcher(name)
//            matcher.matches()
//        }
//        if (result != null) {
//            Arrays.sort(result)
//        }
//
//        return result

        return try {
            Files.list(dir.toPath())
                .use { stream ->
                    stream.filter(Files::isRegularFile) // 只选择常规文件
                        .filter { path -> pattern.matcher(path.fileName.toString()).matches() }
                        .map { it.fileName.toString() }
                        .sorted()
                        .collect(Collectors.toList())
                        .toTypedArray()
                }
        } catch (e: Exception) {
           LogUtils.d(GrifikaDataModule.TAG, "getFiles exception:" + e.message)
            null
        }
    }

    /**
     * Converts a filename globbing pattern to a regular expression.
     * <p>
     * The regex is suitable for use by Matcher.matches(), which matches the entire string, so
     * we don't specify leading '^' or trailing '$'.
     */
    private fun globToRegex(glob: String): String {
        // Quick, overly-simplistic implementation -- just want to handle something simple
        // like "*.mp4".
        return buildString {
            for (ch in glob) {
                when (ch) {
                    '*' -> append(".*")
                    '?' -> append('.')
                    '.' -> append("\\.")
                    else -> append(ch)
                }
            }
        }
    }

    /**
     * Obtains the approximate refresh time, in nanoseconds, of the default display associated
     * with the activity.
     * <p>
     * The actual refresh rate can vary slightly (e.g. 58-62fps on a 60fps device).
     */
    fun getDisplayRefreshNsec(activity: ComponentActivity) : Long{
        val displayManager = activity.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
        val refreshRate = displayManager.displays.first().refreshRate
        return Math.round(1E9/refreshRate).toLong()
    }
}